package filters;

import java.io.IOException;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import admin.data.GeoData;

import controllers.CityServlet;

import systems.ConfigSystem;

import models.GeoModel;
import models.StaffModel;
import models.UserModel;
import models.SiteConfigModel;

public final class UrlFilter implements Filter {

	public void doFilter(ServletRequest request, ServletResponse response,
			FilterChain chain) throws IOException, ServletException {
		HttpServletRequest req = (HttpServletRequest) request;
		HttpServletResponse resp = (HttpServletResponse) response;
		SiteConfigModel config = ConfigSystem.getConfigs();

		HttpSession session = req.getSession();

		UserModel user = null;
		StaffModel staff = null;
		if (session.getAttribute("user_logged_in") != null) {
			user = (UserModel) session.getAttribute("user_logged_in");
		}

		if (session.getAttribute("staff_logged_in") != null) {
			staff = (StaffModel) session.getAttribute("staff_logged_in");
		}

		request.setAttribute("user_logged_in", user);
		request.setAttribute("staff_logged_in", staff);
		request.setAttribute("config", config);

		// listCity will be get from db.
		GeoData geoData = new GeoData();
		// analysis url to detect get by city request.
		String[] splitted = req.getRequestURI().split("/");
		boolean byCity = false;
		if (splitted.length >= 2) {
			String temp = splitted[1];
			for (GeoModel city : geoData.getAll()) {
				if (city.getAlias().equals(temp)) {
					byCity = true;
					break;
				}
			}
		}
		if (byCity) {
			CityServlet cityServlet = new CityServlet();
			cityServlet.doGet(req, resp);
		} else {
			chain.doFilter(request, response);
		}
	}

	public void destroy() {

	}

	public void init(FilterConfig arg0) throws ServletException {
		// TODO Auto-generated method stub
	}
}